package middleware

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
)

func GinLog() gin.HandlerFunc {
	return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		body, _ := ioutil.ReadAll(param.Request.Body)
		param.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
		//todo traceIdT_Uri 拿不到，在服务器上
		traceId := param.Request.Header.Get("traceId")
		turi := param.Request.Header.Get("T_Uri")
		host := param.Request.Header.Get("host")
		var clientIp = param.ClientIP
		if len(host) > 0 {
			clientIp = host
		}
		//for k,v:=range param.Request.Header{
		//	log.Println(k,v)
		//}
		// 你的自定义格式
		return fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%d|%03f|%v\n",
			clientIp,
			param.TimeStamp.Format("2006-01-02T15:04:05.000Z0700"),
			traceId,
			param.Method,
			param.Path,
			//param.Request.Proto,
			turi,
			body,
			param.StatusCode,
			param.Latency.Seconds()*1000,
			param.BodySize,
		)
	})
}
